// pages/community/index.js
const { get, post } = require('../../utils/request');
const { formatTime } = require('../../utils/util');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        posts: [],
        page: 1,
        pageSize: 10,
        hasMore: true,
        isLoading: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.loadPosts();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.setData({
            page: 1,
            posts: [],
            hasMore: true
        });
        this.loadPosts().then(() => {
            wx.stopPullDownRefresh();
        });
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        if (this.data.hasMore) {
            this.loadPosts();
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage(res) {
        if (res.from === 'button') {
            const { id } = res.target.dataset;
            const post = this.data.posts.find(p => p.id === id);
            return {
                title: post.content.substring(0, 30) + '...',
                path: `/pages/community/post-detail?id=${id}`,
                imageUrl: post.images?.[0]
            };
        }
        return {
            title: '健康食谱社区',
            path: '/pages/community/index'
        };
    },

    async loadPosts() {
        if (this.data.isLoading || !this.data.hasMore) return;

        try {
            this.setData({ isLoading: true });

            const params = {
                page: this.data.page,
                pageSize: this.data.pageSize
            };

            const res = await get('/community/posts', params);
            
            // 格式化帖子数据
            const formattedPosts = res.posts.map(post => ({
                ...post,
                createdAt: formatTime(new Date(post.createdAt))
            }));

            const newPosts = this.data.page === 1 ? 
                formattedPosts : 
                [...this.data.posts, ...formattedPosts];

            this.setData({
                posts: newPosts,
                hasMore: formattedPosts.length === this.data.pageSize,
                page: this.data.page + 1,
                isLoading: false
            });
        } catch (error) {
            console.error('加载帖子失败:', error);
            wx.showToast({
                title: '加载失败',
                icon: 'none'
            });
            this.setData({ isLoading: false });
        }
    },

    // 查看帖子详情
    viewPostDetail(e) {
        const { id } = e.currentTarget.dataset;
        wx.navigateTo({
            url: `/pages/community/detail?id=${id}`
        });
    },

    // 查看食谱详情
    viewRecipe(e) {
        const { id } = e.currentTarget.dataset;
        wx.navigateTo({
            url: `/pages/recipe/detail?id=${id}`
        });
    },

    // 点赞/取消点赞
    async toggleLike(e) {
        const { id } = e.currentTarget.dataset;
        try {
            await post('/community/posts/like', { postId: id });
            
            // 更新本地点赞状态
            const posts = this.data.posts.map(post => {
                if (post.id === id) {
                    return {
                        ...post,
                        isLiked: !post.isLiked,
                        likes: post.isLiked ? post.likes - 1 : post.likes + 1
                    };
                }
                return post;
            });

            this.setData({ posts });
        } catch (error) {
            console.error('点赞操作失败:', error);
            wx.showToast({
                title: '操作失败',
                icon: 'none'
            });
        }
    },

    // 显示评论
    showComments(e) {
        const { id } = e.currentTarget.dataset;
        wx.navigateTo({
            url: `/pages/community/comments?postId=${id}`
        });
    },

    // 分享帖子
    sharePost(e) {
        const { id } = e.currentTarget.dataset;
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
    },

    // 跳转到发布页面
    navigateToPublish() {
        wx.navigateTo({
            url: '/pages/community/publish'
        });
    },

    // 预览图片
    previewImage(e) {
        const { urls, current } = e.currentTarget.dataset;
        wx.previewImage({
            urls,
            current
        });
    }
})